package com.ustc.emailtray;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseListener;
import java.net.URL;

import com.ustc.emailUI.ExceptionNotifyUI;

public class Tray {
	private TrayIcon tray_on,tray_off;
	private SystemTray tray;
	private Image icon_on,icon_off;

	public Tray(MouseListener mouseListener_on, MouseListener mouseListener_off){
		if(SystemTray.isSupported()){
			tray=SystemTray.getSystemTray();
		}
		try {
			URL icon_on_url=getClass().getResource("/icon_on.png");
			icon_on=Toolkit.getDefaultToolkit().createImage(icon_on_url);
			URL icon_off_url=getClass().getResource("/icon_off.png");
			icon_off=Toolkit.getDefaultToolkit().createImage(icon_off_url);
			tray_on=new TrayIcon(icon_on,"You have a new Email!");
			tray_on.setImageAutoSize(true);
			tray_on.addMouseListener(mouseListener_on);
			tray_off=new TrayIcon(icon_off,"James Email Monitor");
			tray_off.setImageAutoSize(true);
			tray_off.addMouseListener(mouseListener_off);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			new ExceptionNotifyUI().showExceptionNotifyUI("System has an exception,it will exit!");
			System.exit(0);
		}
		
	}
	
	public void showTray(boolean hasNewMail){
		if(tray!=null){
			try {
				TrayIcon[] icons=tray.getTrayIcons();
				if(icons.length>0){
					for(TrayIcon icon:icons)
						tray.remove(icon);
				}
				if(hasNewMail)
					tray.add(tray_on);
				else
					tray.add(tray_off);
			} catch (AWTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
		
}
